# -*- coding:utf8 -*- #
# -----------------------------------------------------------------------------------
# ProjectName:   pro_xmpt
# FileName:     base
# Author:      
# Datetime:    2021/12/16 9:00
# Description：
# -----------------------------------------------------------------------------------

import random
import time

from selenium import webdriver
from selenium.common.exceptions import WebDriverException, TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait

from common.util.confUtil.configUtil import Config

readIni = Config()


class Base:
    # 测试环境
    def __init__(self, browser="C", resquestUrl=readIni.get_url()):
        """
        初始化数据
        :param browser:传参确认浏览器
        :param resquestUrl: 访问地址,默认为小鳗平台
        """
        try:
            if browser == "C" or browser == "c" or browser == "Chrome":
                print("正在启动Chrome浏览器！")
                self.driver = webdriver.Chrome()
            elif browser == "F" or browser == "f" or browser == "FireFox":
                print("正在启动Firefox浏览器！")
                self.driver = webdriver.Firefox()
            else:
                raise NameError("NameError: 请输入正确的浏览器名称！")
            # 窗口最大化
            self.driver.maximize_window()
            # 访问地址
            self.driver.get(resquestUrl)
        except WebDriverException as e:
            versionErro = "This version of ChromeDriver only supports Chrome version"
            if versionErro in e.msg:
                print("ERROR: 浏览器驱动版本不支持,请更新版本！")
            else:
                raise e

    def _location_element(self, method, value, element_num="dan"):
        """
        定位元素
        简化定位元素的代码
        :param method:通过什么方法定位元素
        :param value: 定位方法的值
        :param element_num:定位元素的数量为单复数，默认为单数
        :return: 定位的元素
        """
        if method == "i" or method == "id" or method == "ID":
            locatMethod = (By.ID, value)
        elif method == "n" or method == "N" or method == "name" or method == "NAME":
            locatMethod = (By.NAME, value)
        elif method == "c" or method == "C" or method == "class" or method == "CLASS_NAME":
            locatMethod = (By.CLASS_NAME, value)
        elif method == "s" or method == "S" or method == "css" or method == "CSS_SELECTOR":
            locatMethod = (By.CSS_SELECTOR, value)
        elif method == "t" or method == "T" or method == "tag" or method == "TAG_NAME":
            locatMethod = (By.TAG_NAME, value)
        elif method == "x" or method == "X" or method == "xpath" or method == "XPATH":
            locatMethod = (By.XPATH, value)
        elif method == "l" or method == "L" or method == "link" or method == "NAME":
            locatMethod = (By.LINK_TEXT, value)
        elif method == "p" or method == "P" or method == "name" or method == "NAME":
            locatMethod = (By.PARTIAL_LINK_TEXT, value)
        else:
            raise NameError("请输入正确的定位方法!")
        try:
            if element_num == "dan":
                return WebDriverWait(self.driver, 10).until(ec.presence_of_element_located(locatMethod))
            else:
                return WebDriverWait(self.driver, 10, 0.01).until(ec.presence_of_all_elements_located(locatMethod))
        except TimeoutException as timOut:
            print(f"ERROR: {timOut.msg}")

    def send_input(self, path, value):
        js = f"document.getElementByTagName('{path}')[0].value = '{value}'"
        self.driver.execute_script(js)

    def send_keys(self, path, value, method="x"):
        """
        输入内容
        :param path: 定位的路径
        :param method: 通过什么方法定位元素
        :param value: 输入的值
        :return: None
        """
        # 定位元素位置
        elements = self._location_element(method, path)
        # 清空
        elements.clear()
        # 输入内容
        if elements is None:
            pass
        else:
            elements.send_keys(value)

    def click(self, value, method="x", element_num="dan"):
        """
        点击
        :param element_num:
        :param method:  通过什么方法定位元素
        :param value: 定位方法的值
        :return: None
        """
        try:
            elements = self._location_element(method, value, element_num)
            if element_num == "dan":
                elements.click()
                time.sleep(0.5)
            else:
                print(elements)
                elements[0].click()
        except AttributeError as ae:
            print(f"ERROR: {ae}")
            raise ae

    def switch_to_frame(self, method, value):
        """
        进入Iframe框架
        :param value:
        :param method: 框架ID
        :return: None
        """
        elements = self._location_element(method, value)
        self.driver.switch_to.frame(elements)

    def switch_to_parent(self):
        """
        退出到iframe框架上一层
        :return:
        """
        self.driver.switch_to.parent_frame()

    def switch_to_default_content(self):
        """
        退到最外层iframe框架
        :return:
        """
        self.driver.switch_to.default_content()

    def random_choice(self, value, method="x"):
        """
        随机点击
        :param method: 定位方法
        :param value: 定位方法所对应的值
        :return:
        """
        elements = self._location_element(method, value, element_num="shuang")
        random.choice(elements).click()

    def select(self, method, value):
        randomSelect = self._location_element(method, value)
        select = Select(randomSelect)
        select.select_by_index(random.randint(1, select.options.length))

    def second_location(self, value, value1, method=By.XPATH, method1=By.TAG_NAME, choice=1):
        """
        二次定位
        :param value: 父级定位方法所对应的值
        :param value1: 子级定位方法所对应的值
        :param method: 父级的定位方法
        :param method1: 子级的定位方法
        :param choice: 随机选择数
        :return: None
        """
        elements = self.driver.find_element(method, value).find_elements(method1, value1)
        if choice == 1:
            random.choice(elements).click()
        else:
            choiceLlist = random.choices(elements, k=random.randint(1, 4))
            for i in choiceLlist:
                i.click()

    def quit(self):
        """
        退出浏览器
        :return:
        """
        self.driver.quit()

    def get_element_text(self, value, method="x"):
        """
        获取文本
        :param method: 定位方法
        :param value: 定位方法所对应的值
        :return: 返回获取到的文本
        """
        return self._location_element(method, value).text

    def save_screenshot(self, filename):
        """
        截图：整个屏幕
        :param filename: 图片路径
        :return:
        """
        self.driver.save_screenshot(filename)

    def get_screenshot_as_file(self, filename):
        """
        截图：整个屏幕
        :param filename: 图片路径
        :return:
        """
        self.driver.get_screenshot_as_file(filename)

    def js_click(self, value, method="x"):
        """需要滚动才能看见的按钮"""

        submit_btn = self._location_element(method, value)
        self.driver.execute_script("arguments[0].click();", submit_btn)


if __name__ == '__main__':
    b = Base()

    # pass
